package com.juntos.quizes.canadaDay.quiz {
	
	import caurina.transitions.Equations;
	import caurina.transitions.Tweener;
	
	import com.juntos.quizes.canadaDay.events.AnswerEvent;
	import com.juntos.quizes.canadaDay.events.QuizEvent;
	import com.juntos.quizes.canadaDay.interactiveElements.QuizButton;
	import com.juntos.quizes.canadaDay.model.Canadian;
	import com.juntos.quizes.canadaDay.model.Key;
	
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextFieldAutoSize;

    [Event ( name="quizComplete", type="com.juntos.quizes.canadaDay.events.AnswerEvent" )]
    [Event (name="disableSelection", type="com.juntos.quizes.canadaDay.events.AnswerEvent" )]
    [Event (name="nextQuestion", type="com.juntos.quizes.canadaDay.events.QuizEvent")]
    [Event (name="submitAnswer", type="com.juntos.quizes.canadaDay.events.QuizEvent")]

    /**
     *@author ghostmonk - 2009-06-24
     */
    public class Quiz extends QuizLayoutAsset {
    	
    	
    	
    	private var _questions:Array;
    	private var _images:Array;
    	private var _currentQuestion:int;
    	private var _score:int;
    	
    	private var _question:String;
        private var _correctMsg:String;
        private var _wrongMsg:String;
    	
    	private var _submitString:String;
    	private var _currentAnswer:int;
    	private var _currentChoice:int;
    	
    	private var _result1:String;
    	private var _result2:String;
    	private var _result3:String;
    	private var _result4:String;
    	private var _closeMsg:String;
    	
    	private var _quizButton:QuizButton;
    	
    	private var _yourResults:String;
    	private var _youGot:String;
    	private var _of:String;
    	private var _forATotal:String;
    	
    	
        public function Quiz( key:Key, baseUrl:String, quizData:XML, buttonText:XML ) {
            
            _questions = new Array();
            _images = new Array();
            _currentQuestion = 0;
            _score = 0;
            
            _quizButton = new QuizButton( navButton, buttonText.@submit, buttonText.@next );
            _quizButton.addEventListener( QuizEvent.NEXT_QUESTION, nextQuestion );
            _quizButton.addEventListener( QuizEvent.SUBMIT_ANSWER, onSubmit );
            
            _question = quizData.question;
            _correctMsg = quizData.correct;
            _wrongMsg = quizData.incorrect;
            
            createQuiz( key, baseUrl );
            nextQuestion( null );
            
            _result1 = quizData.result1;
            _result2 = quizData.result2;
            _result3 = quizData.result3;
            _result4 = quizData.result4;
            _closeMsg = quizData.closeMsg;
            
            _yourResults = quizData.yourResults.part1;
            _youGot = quizData.yourResults.part2;
            _of = quizData.yourResults.part3;
            _forATotal = quizData.yourResults.part4;
            
            removeChild( finalResult );
            finalResult.alpha = 0;
            
            removeChild( closeMsg );
            closeMsg.alpha = 0;
            
        }
        
        
        
        private function enableNav():void {
        	
        	_quizButton.buildIn();
            _quizButton.enable();
            
        }
        
        
        
        public function nextQuestion( e:QuizEvent ):void {
        	
        	if( _currentQuestion == 10 ) {
                addScore();
            }
            else {
            	if( e ) dispatchEvent( e );
	        	_quizButton.disable();
	        	_quizButton.buildOut();
	        	
	        	if( _currentQuestion > 0 ) {	        	
		            ( _images[ _currentQuestion - 1 ] as LoadingImage ).buildOut();
	            }
	        	
	        	questionTracker.text = "Question " + ( _currentQuestion + 1 ) + "/10";
	        	output.text = _question;
	        	_currentAnswer = ( _questions[ _currentQuestion ] as Canadian ).index;
	        	
	        	var image:LoadingImage = _images[ _currentQuestion ];
	        	image.x = imageLoc.x;
	        	image.y = imageLoc.y;
	        	addChild( image );
	        	image.buildIn();
	        	
	            _currentQuestion++;
            }
        }
        
        
        
        public function set choice( value:int ):void {
        	
        	_currentChoice = value;
        	
        	if( _quizButton.isEnabled == false ) {
        	   enableNav();
        	}
        	
        }
        
        
        
        private function createQuiz( key:Key, baseUrl:String ):void {
        	
            var randomIndices:Array = find10Randomindexes();
             
            for each( var integer:int in randomIndices ) {
                var canadian:Canadian = key.answerHash[ integer ]; 
                _questions.push( canadian );
                _images.push( new LoadingImage( baseUrl + "images/" + canadian.image ) );
            }
            
        }
        
        
        
        private function find10Randomindexes():Array {
        	
        	var output:Array = new Array();
        	var rand:int;
        	
        	while( output.length < 10 ) {
        		rand = randomNumber;
        		if( output.indexOf( rand ) == -1 ) {
        			output.push( rand );
        		}
        	}
        	
        	return output;
        	
        }
        
        
        
        private function get randomNumber():int {
        	
        	return int( Math.min( 19, Math.floor( Math.random() * 20 ) ) ) + 10;
        	
        }
        
        
        
        public function startSubmitURL( endpoint:String, email:String ):void {
        	
        	_submitString = endpoint + "?email=" + email;
        	
        }
        
        
        
        private function addAnswer():void {
        	
        	var isRight:Boolean = _currentChoice == _currentAnswer;
        	
        	if( isRight ) {
        		_score++;
        		Tweener.addTween( output, { _text:_correctMsg, time:0.4, transition:Equations.easeNone } );
        	}
        	else {
        		var response:String = _wrongMsg + " " + ( _questions[ _currentQuestion - 1 ] as Canadian ).name + ".";
        		Tweener.addTween( output, { _text:response, time:0.4, transition:Equations.easeNone } );
        	}
        	
        	_submitString += "&" + _currentAnswer + "=" + isRight;
        	dispatchEvent( new AnswerEvent( AnswerEvent.DISABLE_SELECTION, _currentAnswer, isRight ) );
        	
        }
        
        
        
        private function addScore():void {
        	
        	_submitString += "&score=" + _score;
        	submitScore();
        	
        }
        
        
        
        private function submitScore():void {
        	
        	if( CanadaDayQuiz.DEBUG == false ) {
        	   //new URLLoader( new URLRequest( _submitString ) );
        	}
            dispatchEvent( new AnswerEvent( AnswerEvent.QUIZ_COMPLETE, _score ) );
            buildOut();
            setFinalScreen();
        	
        }
        
        
        
        private function onSubmit( e:QuizEvent ):void {
        	
        	dispatchEvent( e );
        	addAnswer();
        	
        }
        
        
        
        private function buildOut():void {
        	
        	_quizButton.buildOut();
        	( _images[ _currentQuestion - 1 ] as LoadingImage ).buildOut();
        	Tweener.addTween( questionTracker, { _text:"", time:0.4, transition:Equations.easeNone, onComplete:removeChildren } );
        	Tweener.addTween( output, { _text:"", time:0.4, transition:Equations.easeNone } );
        	
        }
        
        
        
        private function removeChildren():void {
        	
        	removeChild( navButton );
        	removeChild( output );
        	removeChild( questionTracker );
        	
        }
        
        
        private function setFinalScreen():void {
        	
        	var results:String = _yourResults + ":\n" + _score + " " + _of  + " 10 " + _forATotal + "\n\n " +  ( _score * 10 ) + " %\n\n";
        	
        	finalResult.autoSize = TextFieldAutoSize.RIGHT;
        	closeMsg.autoSize = TextFieldAutoSize.RIGHT;
        	
        	if( _score <= 3 ) {
        		finalResult.text = results + _result1;
        	}
        	else if( _score <=6 ) {
        		finalResult.text = results + _result2;
        	}
        	else if( _score <= 9 ) {
        		finalResult.text = results + _result3;
        	}
        	else if( _score == 10 ) {
        		finalResult.text = results + _result4;
        	}
        	
        	closeMsg.text = _closeMsg;
        	
        	addChild( finalResult );
        	addChild( closeMsg );
        	
        	finalResult.x = ( stage.stageWidth - finalResult.width ) * 0.5;
        	closeMsg.x = ( stage.stageWidth - closeMsg.width ) * 0.5;
        	
        	var yPos:int = ( stage.stageHeight - finalResult.height ) * 0.5;
        	var closeMsgY:int = yPos + finalResult.height + 20;
        	
        	finalResult.y = stage.stageHeight - finalResult.height;
        	closeMsg.y = stage.stageHeight - closeMsg.height;
        	
        	Tweener.addTween( finalResult, { y:yPos, time:0.3, alpha:1, transition:Equations.easeNone } );
        	Tweener.addTween( closeMsg, { y:closeMsgY, time:0.3, alpha:1, transition:Equations.easeNone } );
        	
        	
        	
        }
        
        
        
        
        
        
    }
}